package com.sudo.api.interceptor;

import com.sudo.common.annotation.ApiAuthorization;
import com.sudo.common.utils.HttpUserInfoUtil;
import com.sudo.common.utils.JsonRes;
import com.sudo.common.utils.RetResponse;
import com.sudo.service.admin.service.AdminBaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 为道日损 2020-05-06 23:55
 * webSite：https://www.sudo.ren
 */
@Order(4)
@Component
public class AuthorizationInterceptor extends AdminBaseService implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String username = HttpUserInfoUtil.getSessionUser(request);
        String roleCode = getRoleCodeFromRedisByUsername(username);
        if (StringUtils.isBlank(roleCode)) {
            RetResponse.res(response, JsonRes.errorMsg("暂无权限"));
            return false;
        }
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            ApiAuthorization apiAuthorization = method.getMethodAnnotation(ApiAuthorization.class);
            if (null == apiAuthorization) {
                return true;
            }
            String menuCode = apiAuthorization.menu();
            String buttonCode = apiAuthorization.button();
            //判断是否有按钮权限
            Boolean flag = stringRedisUtil.sIsMember(redisKeys.redisRolePermission(roleCode,menuCode), buttonCode);
            if (flag) {
                return true;
            }
            RetResponse.res(response, JsonRes.errorMsg("暂无权限"));
            return false;
        }else{
            return true;
        }
    }

}
